package com.demo.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.demo.common.base.entity.BaseEntity;
import com.demo.common.utils.ShiroUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MyBatisPlus 自动填充Hander
 */
@Component
@Slf4j
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
    @Override
    @SneakyThrows
    public void insertFill(MetaObject metaObject) {
        /*if (!SecurityUtils.getSubject().isAuthenticated()) {
            return;
        }*/
        // 待处理对象
        Object obj = metaObject.getOriginalObject();
        if (obj instanceof BaseEntity) {
            this.setInsertFieldValByName("creator", ShiroUtils.getUserId(), metaObject);
            this.setInsertFieldValByName("orgId", ShiroUtils.getUserEntity().getOrgId(), metaObject);
            this.setInsertFieldValByName("createTime", new Date(), metaObject);
        }
    }

    @Override
    @SneakyThrows
    public void updateFill(MetaObject metaObject) {
        /*if (!SecurityUtils.getSubject().isAuthenticated()) {
            return;
        }*/
        // 待处理对象
        Object obj = metaObject.getOriginalObject();
        if (obj instanceof BaseEntity) {
            this.setUpdateFieldValByName("modifier", ShiroUtils.getUserId(), metaObject);
            this.setUpdateFieldValByName("modifyTime", new Date(), metaObject);
        }
    }
}
